package com.joshua.spring.controller;

import com.joshua.spring.entity.bo.TokenInfo;
import com.joshua.spring.entity.em.ResponseEnum;
import com.joshua.spring.entity.form.AuthTokenParam;
import com.joshua.spring.entity.form.OauthTokenParam;
import com.joshua.spring.entity.vo.GlobalResponse;
import com.joshua.spring.entity.vo.TokenInfoVO;
import com.joshua.spring.exception.MicroServiceException;
import com.joshua.spring.property.Oauth2Properties;
import com.joshua.spring.service.UserService;
import com.joshua.spring.util.OkHttp3Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


import static com.joshua.spring.constants.FormatterConstants.*;
import static com.joshua.spring.entity.constant.GrantTypeConstants.PWD;
import static com.joshua.spring.entity.constant.GrantTypeConstants.REFRESH;


/**
 * com.joshua.spring.business.controller -- AuthController
 * description:
 *
 * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
 * @date 2020/1/2 15:46
 */
@RestController
@RequestMapping("oauth2")
public class AuthController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Value("${spring.application.name}")
    private String appName;

    @Autowired
    private Oauth2Properties oauthProperties;

    @Autowired
    private UserService userService;

    /**
     * description:
     * "username": "zhangsan",
     * "password": "123456LL",
     * "authType":"PASSWORD"
     *
     * @param param {@link AuthTokenParam }
     * @return {@link GlobalResponse}
     * @author <a href="mailto:joshualwork@163.com">joshua_liu</a>
     * @date 2020/1/7 9:01
     */
    @PostMapping("token")
    public GlobalResponse token(@RequestBody AuthTokenParam param) throws Exception {
        ServiceInstance serviceInstance = loadBalancerClient.choose(appName);
        String url = String.format(URL_FORMATTER, serviceInstance.getHost(), serviceInstance.getPort(), oauthProperties.getOauth2TokenUri());
        //可以添加异步登录日志
        OauthTokenParam tokenParam = OauthTokenParam.builder()
                .clientSecret(oauthProperties.getClientSecret())
                .clientId(oauthProperties.getClientId())
                .grantType(PWD);
        if (!StringUtils.isEmpty(param.getRefreshToken())) {
            tokenParam.grantType(REFRESH);
        }
        BeanUtils.copyProperties(param, tokenParam);
        if (StringUtils.isEmpty(tokenParam.getPassword())) {
            tokenParam.setPassword(PWD);
        }
        TokenInfoVO result = new TokenInfoVO();
        TokenInfo tokenInfo = OkHttp3Utils.httpPost(url, OkHttp3Utils.MediaEnum.FORM, tokenParam, TokenInfo.class);
        if (!StringUtils.isEmpty(tokenInfo.getCode())) {
            GlobalResponse globalResponse = new GlobalResponse();
            BeanUtils.copyProperties(tokenInfo, globalResponse);
            ResponseEnum responseEnum = ResponseEnum.getResultEnumByCode(globalResponse.getCode());
            throw MicroServiceException.builder(responseEnum);
        }
        BeanUtils.copyProperties(tokenInfo, result);
        return GlobalResponse.buildSuccess(result);
    }

//    @PostMapping("register")
//    public GlobalResponse register(@RequestBody RegisterParam param) throws Exception {
//        //注册成功过可以添加异步注册日志
//        UserAddDTO dto = new UserAddDTO();
//        BeanUtils.copyProperties(param, dto);
//        String password = AuthTypeEnum.PASSWORD.equals(param.getAuthType())
//                ? passwordEncoder.encode(param.getPassword()) : null;
//        dto.setPassword(password);
//        Integer result;
//        result = userService.addUser(dto);
//        if (result > 0) {
//            AuthTokenParam tokenParam = new AuthTokenParam();
//            BeanUtils.copyProperties(param, tokenParam);
//            return token(tokenParam);
//        }
//        throw MicroServiceException.builder(ResponseEnum.FAIL);
//    }

    @GetMapping("verifyCode/type/{type}/email/{email}")
    public GlobalResponse emailVerifyCode(@PathVariable String type, @PathVariable String email) {
        //根据verifyCode:$type:email:$email生成redisKey，生成随机数作为value存进redis
        //使用消息队列异步发送邮
        return GlobalResponse.buildSuccess();
    }

}
